package {
	import Classes.CLoader;
	import Classes.ab_access;
	import Classes.pi_events;
	import Classes.pi_images;
	
	import SEApp.dialogs.se_dialog;
	
	import UIFree.ObjectEvent;
	import UIFree.components.uif_window;
	import UIFree.controls.uif_button;
	import UIFree.controls.uif_checkbox;
	import UIFree.controls.uif_close;
	import UIFree.controls.uif_gbutton;
	import UIFree.controls.uif_imageButton;
	import UIFree.controls.uif_input;
	import UIFree.controls.uif_label;
	import UIFree.controls.uif_list;
	import UIFree.controls.uif_scrollbar;
	import UIFree.controls.uif_searchList;
	import UIFree.uif_component;
	import UIFree.uif_ecomponent;
	import UIFree.uif_fontContent;
	import UIFree.uif_loader;
	
	import UIUtils.uif_util;
	
	import api_servers.api_externalserver;
	import api_servers.api_myserver;
	import api_servers.pi_myserver;
	import api_servers.pi_servers;
	
	import com.adobe.images.JPGEncoder;
	
	import components.pj_GenImage;
	import components.pj_albums;
	import components.pj_button;
	import components.uif_center100;
	import components.uif_loaderBar;
	
	import dialogs.*;
	
	import editor.*;
	
	import flash.display.Bitmap;
	import flash.display.BitmapData;
	import flash.display.StageDisplayState;
	import flash.display.StageScaleMode;
	import flash.events.Event;
	import flash.events.IOErrorEvent;
	import flash.events.MouseEvent;
	import flash.events.SecurityErrorEvent;
	import flash.filters.BlurFilter;
	import flash.geom.ColorTransform;
	import flash.geom.Rectangle;
	import flash.net.FileReference;
	import flash.net.URLRequest;
	import flash.system.Capabilities;
	import flash.system.Security;
	import flash.text.TextField;
	import flash.utils.ByteArray;
	
	import manager.pi_manager;
	
	import templates.pi_templates1;


	[SWF(width="760", height="956", backgroundColor="#FFFFFF")]
	public class photo_inject extends pi_app {
		private var _cardInfo		: Object;
		private var _externalserver	: api_externalserver;
		private var _editor			: pi_editor;
		private var _fullView		: pi_cardbody;
		private var _photo			: pj_GenImage;
		private var _cards			: pi_cards;
		private var _toolbar		: pi_baseToolbar;
		private var _manager		: pi_manager;
		private var _myserver		: api_myserver;
		private var _userData		: Object;
		private var _inBoxWindow	: pi_cardsBox;
		private var _outBoxWindow	: pi_cardsBox;
		private var _balance		: Number;
		private var _majorVersion	: Number;
		private var _requireLoaded  : int;
		private var _alert			: pi_alert;
		private var _extendsLayer	: pi_buttonLayer;
		private var _siteData		: Object;
		
		protected var _albums		: pj_albums;
		protected var _layers		: Array;
		protected var _defaults		: Object;
		
		public static var APPWIDTH	: int = 760;
		public static var APPHEIGHT	: int = 956;
		
		public static const MASK_LOAD_ONLY: int = 1;
		public static const FULL_LOAD: int = 2;
		
		public const PRELOADER_PRESENT: Boolean = false;
		
		public function get externalserver(): api_externalserver {
			return _externalserver;
		}
		
		public function get majorVersion(): Number {
			return _majorVersion
		}
		
		public function get myserver(): api_myserver {
			return _myserver;
		}
		
		public function get cardbody(): pi_cardbody {
			if (_editor != null) return _editor.cardBody;
			return _fullView;
		}
		
		public function get editor(): pi_editor {
			return _editor;
		}
		
		public function get manager(): pi_manager {
			return _manager;
		}
		
		public function get photo(): CLoader {
			return _photo;
		}
		
		public function get isFullView(): Boolean {
			return (_fullView != null) && _fullView.visible;
		}
		
		public function get fullScreen(): pi_cardbody {
			return _fullView;
		}
		
		public function get userData(): Object {
			return _userData;
		}
		
		public function get inBoxWindow(): pi_cardsBox {
			return _inBoxWindow;
		}
		
		public function get cards(): pi_cards {
			return _cards;
		}
		
		public function get balance(): Number {
			return _balance?_balance:0;
		}
		
		public function get isPhotoLoaded(): Boolean {
			return (_photo != null) && (_photo.contentLoaderInfo.bytesLoaded > 0);
		}
		
		public function get requireLoaded(): int {
			return _requireLoaded;
		}
		
		override public function getInner(incx: Number=0, incy: Number=0, incw:Number=0, inch:Number=0):Rectangle {
			return new Rectangle(0, 0, APPWIDTH, APPHEIGHT);
		}
		
		public function initLayers(count: int): void {
			_layers = new Array();
			for (var i: int = 0; i<count; i++)
				_layers.push(new uif_ecomponent(this, 0, 76, APPWIDTH, APPHEIGHT - 76));
		}
		
		public function get layers(): Array {
			return _layers;
		}
		
		protected function createExternalServer(): api_externalserver {
			return null;
		}
		
		protected function securityInit(): void {
			for (var i: int=0; i<pi_servers.ADDR.length; i++) {
				Security.allowDomain(pi_servers.ADDR[i]);
				Security.loadPolicyFile(pi_servers.ADDR[i] + '/crossdomain.xml');
			}
		}
		
		protected function extendList(): Object {
			return {};
		}
		
		public function getHost(): String {
			return loaderInfo.url.substr(0, loaderInfo.url.indexOf('/', 8));;
		}
			
		protected function serversInit(): void {
			pi_servers.FLASH_URL		= getHost();
		}
		
		protected function createMyServer(): api_myserver {
			return new pi_myserver(this, pi_servers.ADDR[0] + '/games/index_pj.php', 
						externalserver.vars['app_id'],
						externalserver.secrets[externalserver.vars['app_id']]);
		}
		
		protected function createSiteData(): Object {
			return {};
		}
		
		public function get siteData(): Object {
			return _siteData;
		}
		
		public function get balanceMenu(): Array {
			return [];
		} 
		
		protected function createBanners(level: int): void {
		}
		
		protected function beforeStart(e: Event=null): void {
			
			serversInit();
			uif_loader.CACHE_ENABLED = false;
			_externalserver = createExternalServer();
			pj_extendServices.init(extendList());
			securityInit();
			
			_siteData = createSiteData();
			addEventListener(pi_events.COMPLETEFULLLOAD, doCompleteFullLoad);
			
			resize(APPWIDTH, APPHEIGHT);
			initLayers(6);
			var _loader: pi_loader = new pi_loader(_layers[5], 10, 40, 100, 60, 'tabBlock');
			dispatchEvent(new Event(GDataEvent.REQUEST)); // Обозначаем начало работы
			
			
			var img_loader: pi_imageLoader = new pi_imageLoader(_layers[5], 10, 40, 100, 60, 'tabBlock');
			_extendsLayer = new pi_buttonLayer(_layers[1], APPWIDTH - 250, 5, 250, 10);
			
			
			_myserver	= createMyServer();
			_photo		= new pj_GenImage(this);
			checkVersion();
			
			pi_data.maskInfoList = pi_data.maskInfoList.concat(pi_templates1.maskInfoList);
			pi_data.resetData(pi_data.maskInfoList);
//			pi_data.resetGroupList(pi_data.grMaslen);
			pi_data.resetGroupList(pi_data.Group8);
//			pi_data.resetGroupList(pi_data.Group9);
		}
		
		public function loadGroupMI(groupObj: Object, doComplete: Function): void {
			var loader: CLoader = new CLoader(this, pi_servers.PLUGINS_URL + groupObj.url + '?' + externalserver.vars['ver'], function(e: Event): void {
				var lData: Array = loader.content['data'];
				classes.data.resetData(lData, groupObj.group, false);
				classes.data.maskInfoList = classes.data.maskInfoList.concat(lData);
				loader.dispose();
				delete(groupObj.url);
				doComplete(groupObj);
			})
		}
		
		public function loadGroupMIAll(doComplete: Function, idCard: uint=0): void {
			var loadCount: int = 0;
			
			function doLoad(groupObj: Object): void {
				loadCount--;
				if (loadCount == 0) doComplete();
			}

			function load(item: Object): void {
				loadGroupMI(item, doLoad);
				loadCount++;
			}
			
			var list: Array = classes.data.cardGroup;
			for (var index: int=0; index<list.length; index++) {
				var item: Object = list[index]; 
				if (item.hasOwnProperty('url')) {
					if (idCard != 0) {
						if (item.hasOwnProperty('range')) {
							if ((idCard >= item.range[0]) && (idCard <= item.range[1])) {
								load(item);
								break;
							}
						} else load(item);
					} else load(item);
				}
			}
			if (loadCount == 0) doComplete();
		}
		
		public function photo_inject() {
			super();
			if (stage) beforeStart();
			else addEventListener(Event.ADDED_TO_STAGE, beforeStart);
		}
		
		protected function doCompleteFullLoad(e: ObjectEvent): void {
			if (e.object == _fullView) _fullView.slideShow();
		}
		
/*		public function loadExtendServices(extend: Object, initFunc: Function = null): void {
			if (!_extendLoaded) _extendLoaded = new Object();
			var _this: Object = this;
			var _loadCount: int = 0;
			for (var i: String in extend) {
				if (!_extendLoaded[i] && pi_data.extendServices[i]) {
					_extendLoaded[i] = new CLoader(this, pi_data.extendServices[i] + '?ver=' + externalserver.vars['ver'], 
						function(e: Event): void {
//						_extendLoaded[i] = e.target.content; 
						e.target.content.init(_this, _extendsLayer);
						_loadCount--;
						if (_loadCount == 0) {
							if (initFunc != null) initFunc();
							dispatchEvent(new ObjectEvent(pi_events.PLUGINSCOMPLETE, extendObjects));	
						} 
					});
					_loadCount++;
				}
			}
			if ((_loadCount == 0) && (initFunc != null)) initFunc(); 
		}*/
		
		public function get extendsLayer(): pi_buttonLayer {
			return _extendsLayer;
		}
		
		public function get extendObjects(): Object {
			return pj_extendServices.loaded();
		}
		
		protected function createManager(): pi_manager {
			return null;
		}
		
		public function get def(): Object {
			return _defaults;
		} 
		
		protected function initDefaults(user: Object): Object {
			return {};
		}
		
		protected function doReplyAsCard(): void {
			initEditor();
		}
		
		protected function startViewCard(params: String): void {
			viewCard(pi_cardbody.unpackInfo(params));
			new pj_button(topLayer, (width - 200) / 2, 0, 200, pi_data.REPLYCARD, function(e: Event): void {
				(e.target as pj_button).dispose();
				if (fullScreen) fullScreen.dispose();
				doReplyAsCard();
			});
		}
		
		public function initialize(params: Object = null): void {
//			alert(pi_data.WARNING, '<font size="14" color="#DD0000">Приложение не может соединиться с сервером!</font>\nПопробуйте зайти в приложение позже.\nПросим прощения за доставленные не удобства.');
			externalserver.getProfiles(
				externalserver.viewer_id
			//	'6489426496294592791'
			, function(data: *): void {
				if (data[0]) {
					_userData = data[0];
					var userYear: int = parseInt(_userData.birthday.split('.')[2]);
					if (userYear) _userData.age = (new Date()).fullYear - userYear;
					else _userData.age = 30;
					
//					Акция: сохранения бесплатно!
//					_userData.isPaidLimit = true;
				}
				_defaults = initDefaults(_userData);
				_manager = createManager();
				createBanners(0);
				fullScreenButton();
				
				var a_state: String = params?params['state']:'';
				var info: Object = pi_cardbody.unpackInfo(a_state);
				if (info) {
					if (info.sid) {
						myserver.getCard(externalserver.viewer_id, info.sid, function(data: Object): void {
							if (data.response[0]) startViewCard(data.response[0].params)
							else initEditor(info?info:a_state);
						});
					} else if (info.cardID) {
						if (info.photo) viewCard(info);
						else initEditor(info);
					} else initEditor(info);
				} else initEditor(info?info:a_state);
				dispatchEvent(new GDataEvent(GDataEvent.RESPONSE,  {
					queryID:'startAPP',
					response: {}
				})); // Обозначаем конец начала работы
				
				if (externalserver.vars['StID']) // Если ведется статистика по удачным стартам
					myserver.successStart(externalserver.viewer_id, _majorVersion);
			}, '', 'init_from_user');
		}
		
		protected function changeScreenMode(): void {
			if (stage.displayState == StageDisplayState.NORMAL) {
				if ((stage.fullScreenHeight < this.height) ||
					(stage.fullScreenWidth < this.width))
					stage.scaleMode		= StageScaleMode.SHOW_ALL;
				else stage.scaleMode 	= StageScaleMode.NO_SCALE;
				stage.displayState 		= StageDisplayState.FULL_SCREEN;
			} else {
				stage.scaleMode		= StageScaleMode.NO_SCALE;
				stage.displayState	= StageDisplayState.NORMAL;
			}
		}
		
		protected function fullScreenButton(): void {
			var fsb: uif_imageButton = new uif_imageButton(topLayer, pi_servers.IMAGESURL + 'fullScreen.png', 3, 3, function(e: Event): void {
				changeScreenMode();
			});
			fsb.alpha = 0.5;
			fsb.hint = 'Перейти в полноэкранный режим';
		}
		
		public function get topLayer(): uif_ecomponent {
			return _layers[_layers.length - 1];
		}
		
		protected function parseParams(a_state: String): void {
			var params: Array = a_state.split('~');
			if (params.length > 1) {
				for (var i:int = 0; i<params.length; i += 2) {
					dispatchEvent(new ObjectEvent((params[i] as String).toLocaleUpperCase(), params[i + 1]));
				}
			} 
		}
		
		public function getClasses(): Object {
			var classes: Object = {
				c_app				: pi_app,
				c_externalserver	: api_externalserver,
				services		: pi_servers,
				toolbar			: pi_baseToolbar,
				toolbarButton	: pi_toolbarButton,
				closeButton		: pi_close,
				label			: uif_label,
				button			: uif_button,
				buttonGlow		: uif_gbutton,
				buttonPJ		: pj_button,
				imagebutton		: uif_imageButton,
				closeButton		: uif_close,
				data			: pi_data,
				app				: pi_app,
				window			: uif_window,
				dialog			: se_dialog,
				cardbody		: pi_cardbody,
				component		: uif_ecomponent,
				input			: uif_input,
				images			: pi_images,
				loaderBar		: uif_loaderBar,
				myserver		: pi_myserver,
				list			: uif_list,
				searchlist		: uif_searchList,
				bitmap			: Bitmap,
				bitmapdata		: BitmapData,
				friendsDialog	: pi_checkFriends,
				scrollbar		: uif_scrollbar,
				scrollbar100	: uif_center100,
//				loader			: uif_loader,
				loader			: CLoader,
				bitmap			: Bitmap,
				bitmapData		: BitmapData,
				fontContent		: uif_fontContent,
				textField		: TextField,
				util			: uif_util,
				access			: ab_access,
				siteData		: _siteData,
				checkbox		: uif_checkbox,
				tabsBox			: pi_abox,
				source			: pi_source,
				extendServices	: pj_extendServices,
				colorTransform	: ColorTransform,
				blurFilter		: BlurFilter/*,
				popupMenu		: uif_popupMenu*/
			}; 
			return classes;
		}
		
		public function albumAssessFromSend(albumOrPhoto: Object): Boolean {
			return true;
		}
		
		override public function get classes(): Object {
			return getClasses();
		}
		
		public function checkVersion(): Boolean {
			import flash.system.Capabilities;
			var versionNumber:String = Capabilities.version;
			var versionArray:Array = versionNumber.split(",");
			var length:Number = versionArray.length;
			var platformAndVersion:Array = versionArray[0].split(" ");
			_majorVersion = parseInt(platformAndVersion[1]);
			
			return _majorVersion > 8;
		}
		
		public function externalData(data: *): void {
			dispatchEvent(new GDataEvent(GDataEvent.EXTERNALDATA, data));
		}
		
		public function sendCard(): void {
			if (_editor.cardBody.loaded) {
				if (_manager.checkPaidCard(sendCard)) {
//					if (_manager.checkPaidEffects(sendCard)) {
//						checkPhoto(function(): void {
							var dialog: pi_checkFriends = (new pi_checkFriends(_layers[4], 0, 0));
							dialog.description = pi_data.SELECTFRIENDFROMSEND;
							dialog.addEventListener(pi_checkFriends.SELECTUSERS, function(e: ObjectEvent): void {
								_manager.requestSend(e.object as Array);
							});
//						})				
//					}
				}
			} else alert(pi_data.WARNING, pi_data.SELECTPHOTOTEXT);
		}
		
/*		public function checkPhoto(okFunc: Function): void {
			var imageServer: String = photo.sourceUrl.split('/').slice(0, 3).join('/');
			if (imageServer == pi_servers.USERPHOTOHOST)
				alert(pi_data.MESSAGE, pi_data.LIVEFILEWARNING, function(): void {
					okFunc();
				}, true);
			else okFunc();
		}*/
		
		public function fullView(contentInfo: Object, cardInfo: Object =null): void {
			cardInfo = pi_cardbody.union((cardInfo != null)?cardInfo:_cardInfo, contentInfo);
			if (cardInfo != null) {
				_requireLoaded = FULL_LOAD;

				var mi: pi_maskInfo = pi_data.toMaskInfo(cardInfo, cardInfo.matrix);
				
				if (_fullView) _fullView.dispose()
				
				var ir: Rectangle = _layers[2].getInner();
				var ch: int = (ir.width<ir.height)?ir.width:ir.height;
				_fullView = new mi.maskClass(_layers[2], ir.x, ir.y, ir.width, ch, 'fullView');
				_fullView.visible = false;
				_layers[2].childToBack(_fullView);
				_fullView.addEvent(uif_component.CHANGEVISIBLE, function(e: Event): void {
					app.dispatchEvent(new Event(pi_events.FULLVIEWCHANGE));
					if (_editor != null) {
						if (_fullView.visible) {
							_layers[0].slideHide();
							_layers[1].slideHide();
						} else {
							_requireLoaded = MASK_LOAD_ONLY;
							_fullView.dispose();
							_fullView = null;
							_layers[0].slideShow();
							_layers[1].slideShow();
						}
					} else if (!_fullView.visible) _fullView.unloadAll();
				})
				_fullView.addEvent(Event.COMPLETE, function(e: Event): void {
					dispatchEvent(new Event(pi_events.FULLVIEWPHOTOCOMPLETE));
				}, _fullView.card_photo.contentLoaderInfo);
				
//				a_photo = a_photo?a_photo:_photo;
//				if (a_photo) a_photo.duplicate(_fullView.card_photo);
				
				_fullView.setMaskInfo(mi);
//				if (_fullView is pi_pngcard) (_fullView as pi_pngcard).initEffect(cardInfo.effectID);
			}
		}
		
		public function viewCard(info: Object): void {
			if (info) {
				if (info is String) info = pi_cardbody.unpackInfo(info as String);
				
				var mi: Object = pi_data.infoFromID(info.cardID);
				
				function doView(): void {
					var cardInfo: Object = pi_cardbody.union(mi, info);
					
					if (cardInfo) {
						
	//					myserver.receiveCardViewedAsUser(externalserver.viewer_id, cardInfo.cardID);
						if (cardInfo.extend) 
							pj_extendServices.load(cardInfo.extend, initCard);
						else initCard();
						
						function initCard(): void {
	//						if (a_photo) 
								fullView(info, cardInfo);
								
	/*						else {
								var postLoad: Function = function (e: Event): void {
									fullView(info, cardInfo, a_photo);
									removeEventListener(pi_events.PHOTOLOADCOMPLETE, postLoad);
								}
								addEventListener(pi_events.PHOTOLOADCOMPLETE, postLoad);
								_photo.load(new URLRequest(info.photo));
						}*/
					}
				}
				}
				if (mi) doView();
				else loadGroupMIAll(function(): void {
					mi = pi_data.infoFromID(info.cardID);
					if (!mi) mi = pi_data.defaultMI(info.cardID);
					doView();
				}, info.cardID);
			} else alert(pi_data.ERROR, pi_data.BADLINK);
		}
		
		public function loadAlbums(uid: String): void {
			externalserver.getAlbums(uid, function(data: Object): void {
				afterLoadAlbums(uid, data as Array);
			});
		}
		
		protected function albumsPrepare(uid: String, a_albums: Array): Array {
			return a_albums;
		}
		
		protected function afterLoadAlbums(uid: String, a_albums: Array): void {
		}
		
		protected function createToolbar(): pi_baseToolbar {
			return new pi_toolbar(_layers[2], 556);
		}
		
		protected function createEditor(params: Object=null): void {
			
			if (params && params.hasOwnProperty('cardID')) {
				def.DEFAULT_MASK	= params.cardID;
				var info: Object = pi_data.infoFromID(params.cardID);
				if (info) def.DEFAULT_GROUP	= info.group;
				else def.DEFAULT_GROUP = -1;
			}
			
			_requireLoaded = MASK_LOAD_ONLY;
			_cardInfo 	= pi_data.infoFromID(def.DEFAULT_MASK);
			
			_editor 	= new pi_editor(_layers[0], 0, 5, APPWIDTH, 545);
			addEventListener(Event.SELECT, doSelect);
			
			var gnames: Array = new Array();
//			for each (var gitem: Object in pi_data.cardGroup) gnames.push(gitem.name);
			_cards = new pi_cards(_layers[0], pi_data.cardGroup, 0, 592, APPWIDTH, 185, 'tabBox');
			
			loadAlbums(_externalserver.viewer_id);
			
			_toolbar = createToolbar();
			
			addEventListener(pi_events.CHANGEBALANCE, doChangeBalance);
			addEventListener(pi_events.EYERELEASE, doFullView);
			addEventListener(pi_events.PHOTOLOADCOMPLETE, doPhotoLoad);
			addEventListener(pi_events.PAIDLIMIT, function(e: Event): void {
				_userData.isPaidLimit = true;
			});
			
			function l_doStartLoad(e: Event): void {
				dispatchEvent(new ObjectEvent(pi_events.CHANGEEFFECT, def.DEFAULT_EFFECT));
				removeEventListener(pi_events.COMPLETEFULLLOAD, l_doStartLoad);
			}
			addEventListener(pi_events.COMPLETEFULLLOAD, l_doStartLoad);
			
			if (params && params.hasOwnProperty('photo_url'))
				_photo.load(new URLRequest(params.photo_url))
			else if (!_editor.cardBody.card_photo.loaded) {
				_photo.loadPhoto(_userData);
				//_photo.load(new URLRequest(_userData.pic_big?_userData.pic_big:(pi_servers.MROOT_URL + '/' + pi_data.DEFAULTPHOTO)));
			}
			
			if (params) {
				if (params.hasOwnProperty('plugin'))
					pj_extendServices.loadService(params.plugin);
			}
					
			getStartData(afterStartData);
			createBanners(1);
		}
		
		protected function afterStartData(result: Boolean): void  {
			if (!result) alert(pi_data.ERROR, pi_data.SERVERNOACCESS);
		}
		
		public function get toolbar(): pi_baseToolbar {
			return _toolbar;
		}
		
		public function get albums(): pj_albums {
			return _albums;
		}
		
		protected function doPhotoLoad(e: Event): void {
			if (_editor) _editor.assignPhoto(_photo);	
		}
		
		protected function doChangeBalance(e: ObjectEvent): void {
			_balance = parseFloat(String(e.object));
		}
		
		protected function sd_balance(data:*): void {
			if (data.balance) dispatchEvent(new ObjectEvent(pi_events.CHANGEBALANCE, data.balance));
			else {
				alert(pi_data.WARNING, siteData.NULLBALANCEDESC, function(): void {
					dispatchEvent(new Event(pi_events.INVITEDIALOG));
				}, true);
			}
		}
		
		public function getStartData(_handle: Function): void {
			
			function sd_prepaid(data: *): void { // Получаем оплаченный открытки
				var card_ids: Array = new Array();
				for each (var paid: Object in data) {
					if ((paid.service_id >= pi_data.TA_ORDER_START) && 
						(paid.service_id < pi_data.TA_ORDER_START + pi_data.TA_ORDER_SPACE))
						card_ids.push(paid.service_id - pi_data.TA_ORDER_START);
					else if (paid.service_id == pi_data.TA_ORDERTIMELIMIT_SERVICE)
						dispatchEvent(new Event(pi_events.PAIDLIMIT))
					else if (paid.service_id == pi_data.TA_PRESENTFROMCODE)
						siteData.PRESENTCODE = '';
				}
				dispatchEvent(new ObjectEvent(pi_events.CLEARPRICE, card_ids)); // Снимаем с оплаченных цену
			}
			
			function fromInvite(): void {
				//i1731353195984349210
				if (externalserver.vars['referer_type'] == 'invitation') { // Если перешли по приглашению, начисляем рефералу приз
					myserver.setTransaction(externalserver.vars['referer_id'], pi_data.TA_FROMFRIEND, pi_data.FROMFRIENDPRICE, 
							externalserver.viewer_id);
				}
			}
			
			function sd_info(data: Object): void {	// Получаем инфу о пользователе из БД
				if (data['create']) fromInvite(); // Если создали запись, проверяем что пользователь зашел по приглашению
				if (data.hasOwnProperty('sms_table')) {
					var sms_table: Array = data['sms_table'].split(',');
					for (var i:int=1; i<sms_table.length; i++) {
						pi_payDialog.smsTypes[i] = {
							id: i,
							value: Math.round(sms_table[i] / 100)
						}
					}
				}
				_userData.myData = data;
				dispatchEvent(new ObjectEvent(pi_events.CHECKBOX, data));
				_handle(true);
			}
			
			if (_inBoxWindow == null) {
				var user_id: String = _externalserver.viewer_id;
//				user_id = '12040944688673615433';
				myserver.getStartData(user_id, 
					sd_info,
					sd_balance,
					sd_prepaid
					)
			} else _handle(true);
		}
		
		public function saveNotify(e: Event = null): void { // Отмечает если есть сохранение
			if (!_userData.isPaidLimit) myserver.addNoPayCollector(externalserver.viewer_id, cardbody.maskInfo.id); // Отправляем что сохранили бесплатно
		}
		
		public function initEditor(params: Object=null): void {
			pj_extendServices.createButtons();
			createEditor(params);
		}
		
		public function genFileNameCard(): String {
			return externalserver.viewer_id + '_' + MD5.encrypt(cardbody.packInfo()) + '.jpg';
		}
		
		public function download(fileURL: String, onComplete: Function=null): void {
			var l_alert: pi_alert = new pi_alert(layers[5], pi_data.SAVEDESCR, null, true);
			l_alert.okButton.addEvent(MouseEvent.CLICK, function(e: Event): void {				
				var request: URLRequest;
				var fileRef: FileReference;
				var queryObj: Object = {
					queryID:'downloadFile',
					response: {}
				}
				
				function FRDispose(): void {
					fileRef.removeEventListener(Event.COMPLETE, doComplete);
					fileRef.removeEventListener(IOErrorEvent.IO_ERROR, doDLError);
					fileRef.removeEventListener(SecurityErrorEvent.SECURITY_ERROR, doDLError);
				}
				
				function FRClose(e: Event = null): void {
					app.dispatchEvent(new GDataEvent(GDataEvent.RESPONSE, queryObj));
					FRDispose();
				}
				
				function doComplete(e: Event): void {
					alert(pi_data.MESSAGE, pi_data.sprintf(pi_data.SAVED, fileRef.name));
					FRClose();
					if (onComplete != null) onComplete(e);
				}
				
				function doDLError(e: Event): void {
					alert(pi_data.ERROR, '');
					app.dispatchEvent(new GDataEvent(GDataEvent.ERRORDATARESPONSE, queryObj));
					FRDispose();
				}
				
				request = new URLRequest(fileURL);
				fileRef = new FileReference();
				fileRef.addEventListener(Event.COMPLETE, doComplete);
				fileRef.addEventListener(IOErrorEvent.IO_ERROR, doDLError);
				fileRef.addEventListener(SecurityErrorEvent.SECURITY_ERROR, doDLError);
				fileRef.addEventListener(Event.CANCEL, FRClose);
				fileRef.download(request);
				dispatchEvent(new GDataEvent(GDataEvent.REQUEST, queryObj));
			});
			l_alert.show();				
		}
		
		protected function doFullView(e: Event): void {
			if (_fullView && _fullView.visible) {
				_fullView.slideHide();
			} else {
				fullView(pi_cardbody.unpackInfo(_editor.cardBody.packInfo()));
				_photo.duplicate(_fullView.card_photo);
			}
		}
		
		public function alert(title: String, message: String, closeFunc: Function =null, 
							cancelButton: Boolean = false, alertClass: Class = null,
							onShow: Function=null): pi_alert {
			if (!_alert) {
				if (title == this.classes.data.ERROR)
					message += '\n' + this.classes.data.DEVMESSAGE;
				_alert = new (alertClass==null?pi_alert:alertClass)(topLayer, message, closeFunc, cancelButton);
				_alert.title.text = title;
				_alert.show(onShow);
				_alert.addEventListener(uif_window.CLOSEWINDOW, function(e: Event): void {
					_alert = null;
				});
			}
			return _alert;
		}
		
		public function ErrorMyServer(): void {
			alert(pi_data.ERROR, pi_data.SERVERNOACCESS);
		}
		
		public function linkDialog(title: String, link: String, descr: String = '', closeFunc: Function = null): pi_linkDialog {
			var linkD: pi_linkDialog = new pi_linkDialog(_layers[4], link, descr, closeFunc);
			linkD.title.text = title;
			linkD.show();
			return linkD;
		}
		
		public function getLink(): String {
			return 'http://my.mail.ru/cgi-bin/my/app-canvas?appid=' + externalserver.app_id +  '&ref=sp' + externalserver.user_id + '#state=' + cardbody.packInfo();
		}
		
		public function encodeFromJPG(bmd: BitmapData): ByteArray {
			var je: JPGEncoder = new JPGEncoder(80);
			return je.encode(bmd);
		}
		
		protected function doSelect(e: ObjectEvent): void {
			if (e.object is pi_cardPreview) {
				_cardInfo = (e.object as pi_cardPreview).data;
				_editor.loadMask(pi_data.toMaskInfo(_cardInfo));
			} else if (e.object is pi_previewItem) {
				if (!_editor.cardBody)
					_editor.loadMask(pi_data.toMaskInfo(pi_data.maskInfoList[def.DEFAULT_MASK]));
				_photo.loadPhoto(e.object.data);
			}
		}
		
		public function get photoData(): Object {
			return _photo.data;
		}
		
		public function payDialog(postPayFunc: Function = null): void {
//			alert(pi_data.WARNING, 'В связи с аварией на сервере приложения, платежи временно не принимаются. Просим прощения за доставленные неудобства.');
		}
		
		
		public function transaction(price: Number, onComplete: Function=null,
							serviceID: int = pi_data.TA_ORDER_START, params: String = ''): void {
			// Проводим транзакцию
			myserver.setTransaction(externalserver.viewer_id, serviceID, price, params, function(data:*) : void {
					if (data.response[0].result > 0) { // Если успешное проведение транзакции
						dispatchEvent(new ObjectEvent(pi_events.CHANGEBALANCE, balance + price));
						
						if (serviceID == pi_data.TA_ORDERTIMELIMIT_SERVICE) dispatchEvent(new Event(pi_events.PAIDLIMIT)); // Если транзакция снимает за сервис безлимита
						
						if (onComplete != null) onComplete();
					} else ErrorMyServer();
				});
		}
		
		private function error_LoadBox(): void {
			alert(pi_data.WARNING, pi_data.ERRORLOADBOX);
		}
		
		private function prepareSendList(data: *, doComplete: Function): void {
			// Проверяем есть ли такой шаблон, если нет загружаем все дополнительные группы и снова проверяем
			
			var list: Array = new Array();
			var noIDS: Array = new Array();
			
			function refreshList(): void {
				noIDS.splice(0, noIDS.length);
				list.splice(0, list.length);
				
				for (var n:int =0;n<data.length;n++) {
					if (data[n].params is String) data[n].params = pi_cardbody.unpackInfo(data[n].params);
					if (classes.data.infoFromID(parseInt(data[n].params.cardID))) list.push(data[n]);
					else noIDS.push(data[n].params.cardID);
				}
				
				list.sortOn('time');
			}
			
			if (data.length) refreshList();
			
			if (noIDS.length > 0) this.loadGroupMIAll(function(): void {
				refreshList();
				doComplete(list);
			}) else doComplete(list);
		}
		
		private function checkList(list: Array, data: Array, fieldName: String = 'uid'): Array {
			var i	: int;
			var res	: Array = new Array();
			
			var users: Object = {};
			for (i=0; i<data.length; i++) {
				users[data[i].uid] = data[i];
			}
			
			for (i=0; i<list.length; i++) {
				var userData: Object = users[list[i][fieldName]];
				if (userData) {
					list[i].name = pi_app.userName(userData);
					list[i].user = userData;
					res.push(list[i]);
				}
			}
			
			res.sortOn('utime', Array.DESCENDING);
			return res;
		}
			
		public function showInBox(reuqest_count: int = 0) : void {
			if (_inBoxWindow != null) _inBoxWindow.show();
			else {
				myserver.getInBox(externalserver.viewer_id, function(data: Object): void {
					data = data.response[0];
					if (data.error) error_LoadBox();
					else if (data) {
						var countResult: Object = {count:0, reseive_count:0};
						prepareSendList(data, function(list: Array): void {
							if (list.length > 0) {
								for each (var item: Object in list) {
									if (parseInt(item.received) == 1) countResult.reseive_count++;
									countResult.count++;
								}
							}
							
							if (list.length > 0) {
								var uids: String = '';
								for (var i: int = 0; i<list.length; i++) uids += (uids?',':'') + list[i].uid;
								externalserver.getProfiles(uids, function(data:*): void {
									_inBoxWindow = new pi_cardsBox(_layers[4], checkList(list, data));
									showInBox(reuqest_count);
								});
							} else alert(pi_data.WARNING, pi_data.EMPTYBOX);
						});
					}
				});
			}	
		}
		
		public function showOutBox() : void {
			if (_outBoxWindow != null) _outBoxWindow.show();
			else {
				myserver.getOutBox(externalserver.viewer_id, function(data: Object): void {
					data = data.response[0];
					prepareSendList(data, function(list: Array): void {
						if (list.length > 0) {
							var uids: String = '';
							for (var i: int = 0; i<list.length; i++) uids += (uids?',':'') + list[i].sendTo;
							externalserver.getProfiles(uids, function(data:*): void {
								_outBoxWindow = new pi_cardsBox(_layers[4], checkList(list, data, 'sendTo'), false);
								showOutBox();
							});
						} else alert(pi_data.WARNING, pi_data.EMPTYBOX);
					});
				});
			}	
		}
		
		public function saveToJPG(cardbody: Object): void {
			var a_alert: pi_alert = alert(pi_data.MESSAGE, pi_data.JPGWAIT, null, false, null, function(): void {
				var a_bytes: ByteArray = cardbody.asBytes();
				a_alert.close(0, function(): void {
					_manager.saveJPG(a_bytes);
				});
			});
			a_alert.okButton.visible = false;
		}
	}
}
